<?php
/**
 * 用户认证
 * @author solar
 */
class AuthProxy extends BaseProxy
{
	public function noAuthMethod() {
		return array('sinaOAuth2','loginApp','logined');
	}
	
	/**
	 * 新浪oauth2授权
	 * @author solar
	 */
	public function sinaOAuth2() {
		if(empty($_POST["signed_request"])) return $this->fail();
		$o=new SaeTOAuthV2(WB_AKEY,WB_SKEY);
		$data=$o->parseSignedRequest($_POST["signed_request"]);
		if($data=='-2') return $this->fail();
		else if(empty($data["user_id"])) return $this->fail();
		else{
			CoreFactory::session()->set('oauth2',$data);
			CoreFactory::session()->set('sina_id',$data['user_id']);
			CoreFactory::session()->set('sina_token',$data['oauth_token']);
			$userService = ServiceFactory::get('UserService');
			$userRow = $userService->checkSinaUser($data['user_id']);
			if(!$userRow) return $this->fail();
			CoreFactory::session()->set('user_id',$userRow['u_id']);
			CoreFactory::session()->set('user_name',$userRow['u_user_name']);
			ModelFactory::get('SinaModel')->updateToken($data['user_id'],$data['oauth_token']);
			ModelFactory::get('UserModel')->updateLoginStatus($userRow['u_id']);
			$userService->checkHasGroup($userRow['u_id']);
		}
		return array('result'=>1);
	}
	
	/**
	 * 模拟登录应用
	 * @author solar
	 */
	public function loginApp() {
		if(isset($_POST['user_id']))
			$userSinaRow=ModelFactory::get('SinaModel')->getByField(array('u_id'=>$_POST['user_id']));
		else if(isset($_POST['name']))
			$userSinaRow=ModelFactory::get('SinaModel')->getByField(array('name'=>$_POST['name']));
		if(empty($userSinaRow)) return array('result'=>0);
		CoreFactory::session()->set('sina_id',$userSinaRow['sina_id']);
		CoreFactory::session()->set('sina_token',$userSinaRow['token']);
		CoreFactory::session()->set('user_id',$userSinaRow['u_id']);
		CoreFactory::session()->set('user_name',$userSinaRow['screen_name']);
		return array('result'=>1);
	}
	
	/**
	 * 是否已登录
	 * @author solar
	 */
	public function logined() {
		if(ServiceFactory::get('UserService')->isLogined())
			return $this->success();
		else 
			return $this->fail();
	}
	
	/**
	 * 登录
	 * @author solar
	 */
	public function login() {
		if(ServiceFactory::get('UserService')->login($_POST['name'],$_POST['pwd'])) 
			return $this->success();
		else
			return $this->fail();		
	}
	
	/**
	 * 登出
	 * @author solar
	 */
	public function logout() {
		ServiceFactory::get('UserService')->logout();
		return $this->success();
	}
		
}